import React, { useEffect } from "react";
import Head from "next/head";
import "@/styles/globals.scss";
import { PROJ_TITLE } from "@/constant";

const { NEXT_PUBLIC_ENV_BASE_PATH } = process.env;

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector("#jss-server-side");
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
    
    const queryString = window.location.search;
    const locationUrl = window.location.href;
    const webHost = window.location.origin;
    const urlParams = new URLSearchParams(queryString);
    const msgId = "23455504169955371";
    const shared = urlParams.get("shared");
    let originalPage = shared === undefined || shared == null;
    const sharePageUrl = originalPage ? locationUrl + "&shared=true" : locationUrl;
    fetch("http://wechat.sixtest.xyz/api/web/getWXJSConf?messageId=" + msgId + "&locationUrl=" + encodeURIComponent(locationUrl)).then(response => response.json())
      .then(data => {
        let body = data.body;
        (window as any).wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: body.appId, // 必填，公众号的唯一标识
          timestamp: body.timestamp, // 必填，生成签名的时间戳
          nonceStr: body.nonceStr, // 必填，生成签名的随机串
          signature: body.signature,// 必填，签名
          jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"] // 必填，需要使用的JS接口列表
        });
        (window as any).wx.ready(function() {   //需在用户可能点击分享按钮前就先调用 自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）
          (window as any).wx.updateAppMessageShareData({
            title: "视频例句 FROM《球球英语》", // 分享标题
            desc: body.keyWord + " 的视频例句", // 分享描述
            link: sharePageUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: webHost + "/favicon.ico", // 分享图标
            success: function() {
            
            }
          });
        });
        (window as any).wx.ready(function() {      //需在用户可能点击分享按钮前就先调用 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）
          (window as any).wx.updateTimelineShareData({
            title: body.keyWord + " 的视频例句", // 分享标题
            link: sharePageUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: webHost + "/favicon.ico", // 分享图标
            success: function() {
            
            }
          });
        });
      });
    
    
  }, []);
  return <>
    <Head>
      <meta name="viewport"
            content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
      <script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
      <script src={`${NEXT_PUBLIC_ENV_BASE_PATH}/lib/fastclick.js`}></script>
      <script
        dangerouslySetInnerHTML={{
          __html: `
            if ('addEventListener' in document) {
              document.addEventListener('DOMContentLoaded', function() {
                FastClick.attach(document.body);
              }, false);
            }
            if(!window.Promise) {
              document.writeln('<script src="${NEXT_PUBLIC_ENV_BASE_PATH}/lib/es6-promise.min.js"'+'>'+'<'+'/'+'script>');
            }
          `
        }}
      />
      <link rel="icon" href="/favicon.ico"/>
      {/*<link*/}
      {/*  rel="stylesheet"*/}
      {/*  href="https://video-react.github.io/assets/video-react.css"*/}
      {/*/>*/}
      <title>{pageProps.pageTitle || PROJ_TITLE}</title>
      <script dangerouslySetInnerHTML={{
        __html: `
          (function () {
            function IsPC() {
              var userAgentInfo = navigator.userAgent;
              var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
              var flag = true;
              for (var v = 0; v < Agents.length; v++) {
                  if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }
              }
              return flag;
            }
            function getQueryVariable(variable) {
              var query = window.location.search.substring(1);
              var vars = query.split("&");
              for (var i=0;i<vars.length;i++) {
                  var pair = vars[i].split("=");
                  if(pair[0] == variable){return pair[1];}
              }
              return(false);
            }
            // if (IsPC() && getQueryVariable('v_m') !== 'pc') {
            //   window.location.href = window.location.origin + "${NEXT_PUBLIC_ENV_BASE_PATH}/pc-guid?v_m=pc&url=" + encodeURIComponent(window.location.href);
            // }
            if (IsPC() && getQueryVariable('v_m') === 'pc' && !getQueryVariable('url')) {
              window.addEventListener('load', function(){
               document.getElementById('__next').classList.add('pc-mode');
              })
            }
          })();
        `
      }}/>
    </Head>
    <script
      dangerouslySetInnerHTML={{
        __html: `
               window.onresize = function () {
                  getRem(750, 75);
                };
                function getRem(pwidth, prem) {//封装
                    var html = document.getElementsByTagName("html")[0];
                    var oWidth = document.body.clientWidth || document.documentElement.clientWidth;
                    html.style.fontSize = oWidth / pwidth * prem + "px";
                }
                getRem(750, 75);
            `
      }}
    />
    <Component {...pageProps} />
  </>;
}

export default MyApp;
